using NHibernate;
using SmartHRMS.CustomExceptions.Infrastructure;
using SmartHRMS.Infrastructure;
using System;

namespace SmartHRMS.NhibernateRepository
{
    public class NhibernateUnitOfWork : IUnitOfWork
    {
        private ISession _Session;
		
        public NhibernateUnitOfWork()
        {
            _Session = SessionFactory.GetCurrentSession();
        }
		
        public void Save(IAggregateRoot Entity)
        {
            //TODO: Use CurrentSession, this will be from the HttpContext
            _Session.SaveOrUpdate(Entity);
            
        }
		
        public void Commit()
        {
            using (var transaction = _Session.BeginTransaction())
            {
                try
                {
                    transaction.Commit(); // flush the session and commit the transaction
                }
                catch (StaleObjectStateException NHex)
                {
                    transaction.Rollback();
                    // TODO: Log exception
					
                    // Catch StaleObjectStateException:
                    // Entity was changed while we were viewing it,
                    // Wrap Nhibernate exception  and then send it
                    // back up the calling stack
                    throw (new ConcurrencyException("Please reload the screen as changes have been made to an entity since first viewing.", NHex));
                }
                catch (Exception)
                {
                    transaction.Rollback();
                    // TODO: Log exception
                    throw;
                }
            }
        }
		
        public void Delete(IAggregateRoot Entity)
        {
            _Session.Delete(Entity);
        }
    }
}
